<?php
namespace Client\Controller;

use Zend\View\Model\ViewModel;
use Client\Exception\ClientException;
use Zend\Db\Sql\Expression;
use Client\Common\LoggerHelper;

class MyController extends InitializeController
{     
    
    /*
     * 个人中心首页
     */
    public function homeAction()
    {
        $user = $this->getUserTable()->getById($this->user_id);
        
        $data = array(
            'user' => $user
        );
        return new ViewModel($data);
    }
  
    public function saveImgAction(){
    	
        $where = array();
        $data  = array();
        $config = $this->getServiceLocator()->get('Config');
        $where['user_id']=$this->user_id?$this->user_id:123;

        $response=array('status'=>'failed');
        $request=$this->getRequest();
        $data['filename']=$request->getPost("filename");
        $data['fileExt']=$request->getPost("fileExt");
        $data['fileCode']=$request->getPost("fileCode");
        //$imageDir=$config['img']['savepath'];
        //$cdn=$config['img']['cdn'];
        $savePath=$config['img']['savepath'];
        $imgUrl=$config['img']['url'];

        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $data['fileCode'], $result)){
                $type = $data['fileExt'];
                $savePath .= date('Ymd',time())."/";
                $imgUrl .= date('Ymd',time())."/";

                if(!file_exists($savePath))
                {
                        //检查是否有该文件夹，如果没有就创建，并给予最高权限
                        mkdir($savePath, 0777);
                }

                $_filename=uniqid().".{$type}";
                $savePath .= $_filename;
                $imgUrl .= $_filename;

                if (file_put_contents($savePath, base64_decode(str_replace($result[1], '', $data['fileCode'])))){

                        $response['data']['savePath'] = $savePath;
                        $response['data']['imgUrl'] = $imgUrl;
                        $data['image']=$imgUrl;

                        if(empty($data['image'])){
                                $response['reason']="保存图片失败!";
                        }else{

                                $rs = $this->getUserTable()->updateUser($data,$where);
                                if(!empty($rs)){
                                        $response['status']="success";
                                }
                        }

                }else{
                        $response['reason']="保存失败";
                }
        }
                echo json_encode($response);die;
    }

        /**
         * 更新用户信息
         */
    public function updateUserAction(){
        $where = array();
        $data  = array();
        $response=array('status'=>'failed');

        $where['user_id']=$this->user_id?$this->user_id:123;
        $request=$this->getRequest();
        $data['username']=$request->getPost("username");

        if(empty($data['username'])){
                $response['reason']="用户名无效!";
        }else{

                $rs = $this->getUserTable()->updateUser($data,$where);
                if(!empty($rs)){
                        $response['status']="success";
                }

        }

        echo json_encode($response);die;

    }


    /*
     * 信息编辑
     */
    public function infoAction()
    {
        $user = $this->getUserTable()->getById($this->user_id);

        $data = array(
                'user' => $user
        );
        //var_dump($user);
        return new ViewModel($data);
    }
    
    /*
     * 充值页面 
     */
    public function rechargeAction()
    {
        return new ViewModel();
    }
    
    /*
     * 注：需要添加事务
     */
    public function ajaxRechargeSubmitAction()
    {
        $post = $this->request->getPost();
        //充值
        $secret_code = $post['secret_code'];

        
        $user = $this->getUserTable()->getById($this->user_id);
        if (empty($user)) {
            $e = new ClientException(ClientException::USER_NOEXIST_TEXT,ClientException::USER_NOEXIST);
            die(json_encode($e->toJson()));
        }
        
        $rcard = $this->getRechargeCardTable()->getUnusedByCode($secret_code);
        if (empty($rcard)) {
            $e = new ClientException(ClientException::RECHARGE_CARD_NOEXIST_TEXT,ClientException::RECHARGE_CARD_NOEXIST);
            die(json_encode($e->toJson()));
        }
        
        //更新recharge信息
        $rcard->use_time = new Expression('NOW()');
        $rcard->has_use = 1;
        $rcard->user_id = $this->user_id;
        $rcard->save();

        //更新用户账户信息
        $result = $this->getUserTable()->recharge($rcard->amount,$this->user_id);
        
        //添加用户现金流水记录
        $set = array(
            'user_id'=>$user->user_id,
            'ubl_income'=>$rcard->amount,
            'ubl_balance'=>$user->balance+$rcard->amount,
            'ubl_create_time'=>new Expression("NOW()"),
            'ubl_detail'=>"储值卡充值",
        );
        $result = $this->getUserBalanceLogTable()->insert($set);
          
        if($result == true) {
            $response = array(
                'result' => true
            );
        } else {
            $response = array(
                'result' => false
            );
        }
        
        die(json_encode($response));
    }
    
    /*
     * 我的代金券页面
     */
    public function voucherAction()
    {
        $query = array(
            'user_id' => $this->user_id
        );
        $list = $this->getVoucherTable()->getVoucherList($query);
        
        $data = array(
            'list' => $list
        );
        return new ViewModel($data);
    }
    
    public function scanVoucherResultAction()
    {
        $id = $this->params()->fromRoute('id', 0);
        $voucher = $this->getVoucherTable()->getVoucherById($id);
        if(empty($voucher)) {
            $message = '优惠券已领完';
        } else {
            $message = '您已领取成功';
        }
        
        $data = array(
            'voucher' => $voucher,
            'message' => $message
        );
        return new ViewModel($data);
    }
    
    /*
     * 扫码获取代金券
     */
    public function scanVoucherAction()
    {
        $code = $this->params()->fromRoute('code', 0);
        
        $db = $this->getAdapter()->getDriver()->getConnection();
        $db->beginTransaction();
        try
        {
            //检查有会员是否存在
            $voucherType = $this->getVoucherTypeTable()->getByCode($code);
            
            if (empty($voucherType)) {
                throw new ClientException("优惠券不存在");
            }
            
            //检查代金券是否还有库存
            $hasScanCount = $this->getVoucherTable()->getCountById($voucherType->vt_id);
            if ($voucherType->vt_num > $hasScanCount) {
                //添加代金券
                $set = array(
                    'vt_id' => $voucherType->vt_id,
                    'user_id' => $this->user_id
                );
                $this->getVoucherTable()->insert($set);
                $lastOrderId = $this->getVoucherTable()->lastInsertValue;
                
                $db->commit();
                return $this->redirect()->toRoute('my', array(
                    'action' => 'scanVoucherResult',
                    'id' =>$lastOrderId
                ));
            } else {
                
                $db->commit();
                //提示用户代金券已领完
                return $this->redirect()->toRoute('my', array(
                    'action' => 'scanVoucherResult',
                ));
            }                      
        }
        catch(\Exception $e)
        {
            $db->rollBack();
            LoggerHelper::client_exception($e);
            throw new ClientException('5001');
        }      
    }
    
    /*
     * 在线反馈
     */
    public function feedbackAction()
    {
    	$rs=array('userid'=>$this->user_id);
        return new ViewModel($rs);
    }
    
    /*
     * 我的余额
     */
    public function balanceAction()
    {

        $user = $this->getUserTable()->getById($this->user_id);
        
        $query = array(
            'user_id' => $this->user_id
        );
        
        $list = $this->getUserBalanceLogTable()->getList($query);
        
        $data = array(
            'user' => $user,
            'list' => $list
        );
        return new ViewModel($data);
    }
}